package com.hw.pusher.push.huawei;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;

import androidx.core.app.NotificationCompat;

import com.huawei.hms.push.HmsMessageService;
import com.huawei.hms.push.RemoteMessage;
import com.hw.pusher.HWPushActivity;
import com.hw.pusher.R;
import com.hw.pusher.push.PushData;
import com.hw.pusher.push.mi.MiProcessCheck;
import com.hw.pusher.utils.Logger;

public class HuaWeiPushService extends HmsMessageService {
    @Override
    public void onNewToken(String token) {
        super.onNewToken(token);
        Logger.d( "receive token:" + token);
        if (!TextUtils.isEmpty(token))
            handPushMessage("", 0, token);
    }


    /**
     * This method is used to receive downstream data messages.
     * This method callback must be completed in 10 seconds. Otherwise, you need to start a new Job for callback processing.
     *
     * @param message RemoteMessage
     */
    @Override
    public void onMessageReceived(RemoteMessage message) {
        Logger.d( "onMessageReceived is called");
        if (message == null) {
            Logger.d( "Received message entity is null!");
            return;
        }
        Logger.d( "Received message entity is null!"+message.getData());

        handPushMessage(message.getData(), 1, "");
        // getCollapseKey() Obtains the classification identifier (collapse key) of a message.
        // getData() Obtains valid content data of a message.
        // getMessageId() Obtains the ID of a message.
        // getMessageType() Obtains the type of a message.
        // getNotification() Obtains the notification data instance from a message.
        // getOriginalUrgency() Obtains the original priority of a message.
        // getSentTime() Obtains the time when a message is sent from the server.
        // getTo() Obtains the recipient of a message.
//        if (!TextUtils.isEmpty(message.getData())) {
//            generateNotification(getApplicationContext(), "huawei", "华为推送", message.getData());
//        }


    }
    void generateNotification(Context context, String title, String content, String data) {
        String id = "notification_channel_01";
        String channel_name = "channel_name";
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        Notification notification = null;
        Intent intent = new Intent(context, HWPushActivity.class);
        intent.putExtra("_data",data);

        PendingIntent pendingIntent = PendingIntent.getActivity(context,1,intent,PendingIntent.FLAG_UPDATE_CURRENT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(id, channel_name, NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(mChannel);
            notification = new Notification.Builder(context)
                    .setChannelId(id)
                    .setContentTitle(title)
                    .setContentText(content)
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
//                    .setSmallIcon(R.mipmap.ic_launcher)
                    .build();
        } else {
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
                    .setContentTitle(title)
                    .setContentText(content)
//                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
                    .setOngoing(true);//无效
            notification = notificationBuilder.build();
        }
        notificationManager.notify(111123, notification);
    }

    /**
     *
     * @param receivePushData
     * @param action : 0通知推送，１表示透传
     */
    public  void handPushMessage(String receivePushData, int action, String token){
        Context context = getApplicationContext();
        //逻辑分析：
        //1. 如果进程不存活，直接重新启动应用
        //2. 如果进程存活，分为两种情况：
        //    情况1：进程存活，但Task栈已经空了,此时需要重新启动应用,比如用户点击Back键退出应用，但进程还没有被系统回收
        //    情况2：进程存活，Task 栈不为空，也分两种情况：
        //            1：应用在前台，不做任何处理
        //            2：应用在后台，将应用切换到前台
//        if (MiProcessCheck.isAppAlive(context, context.getPackageName())) {
//            Logger.d( "the app process is alive,"+context.getPackageName());
//            if (MiProcessCheck.isTaskEmpty(context)){
//                // 任务栈为空，重新启动app
//                Logger.d( "the app process is alive, task is empty");
//
//                MiProcessCheck.reOpenApp(context, getPushData(receivePushData, action).toJson(), HWPushActivity.BRAND_HUAWEI);
//            }else{
//                // 任务栈不为空，将后台应用放到前台
//                Logger.d( "the app process is alive, task is not empty");
//                MiProcessCheck.setTopApp(context);
//                passMessage(token, receivePushData, action);
//            }
//        } else {
//            // 任务栈为空，重新启动app
//            Logger.d( "the app process is dead");
//            MiProcessCheck.reOpenApp(context, getPushData(receivePushData,action).toJson(), HWPushActivity.BRAND_HUAWEI);
//        }
    }

    PushData getPushData(String message, int action) {
        PushData pushData = new PushData();
        pushData.setType(HWPushActivity.BRAND_HUAWEI);
        pushData.setAction(action);
        pushData.setMessage(message);
        return pushData;
    }

    private void passMessage( String token, String data, int action) {
        PushData pushData = new PushData();
        pushData.setType(HWPushActivity.BRAND_HUAWEI);
        pushData.setToken(token);
        pushData.setAction(action);
        pushData.setMessage(data);
        HWPushActivity.handler.postDelayed(() -> HWPushActivity.handler.sendMessage(HWPushActivity.createMessage(pushData)), 1 * 1000);
    }
}
